package com.augmentum.oes.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.augmentum.oes.dao.mybatis.ExamDaoImpl;
import com.augmentum.oes.dao.mybatis.QuestionDaoImpl;
import com.augmentum.oes.dao.mybatis.UserDaoImpl;
import com.augmentum.oes.exception.DBException;
import com.augmentum.oes.model.Exam;
import com.augmentum.oes.model.Pagination;
import com.augmentum.oes.model.Question;
import com.augmentum.oes.service.ExamService;
import com.augmentum.oes.service.QuestionService;

@Service
public class ExamServiceImpl implements ExamService {
    @Autowired
    private ExamDaoImpl examDao;
    @Autowired
    private QuestionDaoImpl questionDao;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private UserDaoImpl userDao;

    @Override
    @Transactional
    public void createExam(Exam exam) {
        int totalCount = getQuestionCount();
        int needCount = exam.getQuestionQuantity();
        if (needCount <= totalCount && needCount > 0) {
            int examId = examDao.addExam(exam);
            List<Question> list = questionDao.randQ(needCount);
            for (Question question : list) {
                examDao.setToBak(question);
                examDao.setConnection(examId, question.getId());
            }
        } else {
            throw new DBException("Over count");
        }
    }

    @Override
    public void setInfo(Exam exam, String date, String hour, int id) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date effectiveTime = sdf.parse(date + " " + hour);
        exam.setEffectiveTime(effectiveTime);
        exam.setCreatorId(id);
    }

    @Override
    public List<Exam> examList(Pagination<Exam> page) {
        page.setTotalCount(examDao.getExamCount(page.getFuzzyWord()));
        List<Exam> list = examDao.examPage(page);
        for (Exam exam : list) {
            int id = exam.getCreatorId();
            exam.setCreator(userDao.getName(id));
        }
        return list;
    }

    @Override
    public int getQuestionCount() {
        return questionDao.getCount("");
    }

}
